<template>
    <div class="confirm-order-container">
        <!-- 收货地址区域开始 -->
        <div class="address-wrap wrapper" @click="showAddDeliveryAddr">
            <div class="title">
                <i class="iconfont icon-address"></i>
                <span>收货地址</span>
            </div>
            <div class="content">
                <div class="address-right" v-if="userStore.deliveryAddr.name">
                    <div class="name-box">
                        <span class="name">{{userStore.deliveryAddr.name}}</span>
                        <span class="mobile">{{userStore.deliveryAddr.mobile}}</span>
                    </div>
                    <div class="address">{{userStore.deliveryAddr.region}} {{ userStore.deliveryAddr.address }}</div>
                </div>
                <div class="address-right" v-else>
                    <div class="btn" @click="showAddDeliveryAddr">选择收货地址</div>
                </div>

                <i class="iconfont icon-xiangyoujiantou"></i>
            </div>
        </div>
        <!-- 收货地址区域结束 -->


        <!-- 商品信息区域开始 -->
        <div class="goods-wrap wrapper">
            <div class="title">
                <i class="iconfont icon-shangpin"></i>
                <span>商品信息</span>
            </div>

            <!-- 直接购买方式开始 -->
            <div class="content" v-if="mode == 1">
                <div class="goods-item" @click="$router.push({path: '/goods-detail', query: {id: orderStore.createOrderParams.goods_id}})">
                    <div class="cover">
                        <img :src="global.FILE_DOMAIN + orderStore.createOrderParams.cover_url" alt="">
                    </div>

                    <div class="meta">
                        <span class="name ellipsis-2">{{ orderStore.createOrderParams.name }}</span>
                        <span class="sku-txt ellipsis-2">{{ orderStore.createOrderParams.goods_sepc_option_text }}</span>
                        <div class="price-wrap">
                            <div class="price-box">
                                <span class="symbol">￥</span>
                                <span class="price">{{ (orderStore.createOrderParams.price/100).toFixed(2) }}</span>
                            </div>
                            <span class="num">x {{ orderStore.createOrderParams.num }}</span>
                        </div>
                    </div>
                </div>
            </div>
            <!-- 直接购买方式结束 -->

            <!-- 购物车结算方式开始 -->
            <div class="content" v-if="mode == 2">
                <div class="goods-item" v-for="(item, index) in cartStore.checkedList" :key="index" @click="$router.push({path: '/goods-detail', query: {id: item.goods_id}})">
                    <div class="cover">
                        <img :src="global.FILE_DOMAIN + item.goods.cover_url" alt="">
                    </div>

                    <div class="meta">
                        <span class="name ellipsis-2">{{ item.goods.name }}</span>
                        <span class="sku-txt ellipsis-2">{{ item.goods_sepc_option_text }}</span>
                        <div class="price-wrap">
                            <div class="price-box">
                                <span class="symbol">￥</span>
                                <span class="price">{{ (item.goods.price/100).toFixed(2) }}</span>
                            </div>
                            <span class="num">x {{ item.num }}</span>
                        </div>
                    </div>
                </div>
            </div>
            <!-- 购物车结算方式结束 -->
        </div>
        <!-- 商品信息区域结束 -->

        <!-- 订单备注区域开始 -->
        <div class="order-note-wrap wrapper">
            <el-input
                v-model="note"
                :autosize="{ minRows: 2, maxRows: 4 }"
                type="textarea"
                placeholder="请输入订单备注"
            />
        </div>
        <!-- 订单备注区域结束 -->

        <!-- 结算区域开始 -->
        <div class="settlement-wrap wrapper">
            <div class="amount-box">
                <span class="text">商品总价: </span>
                <span class="symbol">￥</span>
                <span class="price" v-if="mode == 1">{{ ((orderStore.createOrderParams.price * orderStore.createOrderParams.num)/100).toFixed(2) }}</span>
                <span class="price" v-else>{{ (cartStore.checkedAmount/100).toFixed(2) }}</span>
            </div>

            <span class="btn" @click="handlerCreateOrder">提交订单</span>
        </div>
        <!-- 结算区域结束 -->

        <!-- 选择地址弹层区域 -->
        <el-drawer v-model="drawer" size="26%" :close-on-click-modal="false">
            <template #header>
                <div class="header-wrap">选择收货地址</div>
            </template>

            <template #default>
                <div class="content-wrap">
                    <div 
                        class="address-item" 
                        v-for="(item, index) in deliveryAddrList"
                        :key="index"
                        :class="item.id == currentAddrId ? 'active': ''"
                        @click="handlerChooseDeliveryAddr(item)"
                    >
                        <div class="top">
                            <span class="name">{{item.name}}</span>
                            <span class="mobile">{{item.mobile}}</span>
                        </div>

                        <div class="bottom">
                            <span>{{item.region}} {{ item.address }}</span>
                        </div>
                    </div>

                    <div class="address-btn">
                        <span @click="$router.push({path: 'user/address'})">新增收货地址+</span>
                    </div>
                </div>
            </template>
        </el-drawer>
    </div>
</template>

<script setup>
import { ref, inject, onMounted } from 'vue'

import { useUserStore } from '@/stores/modules/user'
import { useOrderStore } from '@/stores/modules/order'
import { useCartStore } from '@/stores/modules/cart'

import { useRouter,useRoute } from 'vue-router'
import { reqCreateOrderAPI, reqGenerateOrderAPI } from "@/apis/order"
import { reqUserDeliveryAddrListAPI } from '@/apis/userDeliveryAddr'

import { ElNotification } from 'element-plus'



// ------------------ 定义全局变量开始 ------------------
// 全局属性
const global = inject('global')

// 用户存储
const userStore = useUserStore()

// 购物车存储
const cartStore = useCartStore()

// 订单存储
const orderStore = useOrderStore()

// 路由
const route = useRoute()

// 路由器
const router = useRouter()

// 当前收货地址ID
const currentAddrId = ref(0)

const drawer = ref(false)

// 订单备注
const note = ref('')
// ------------------ 定义全局变量结束 ------------------


const mode = ref(0)
onMounted(() => {
    mode.value = route.query.mode
    if (userStore.deliveryAddr.name == null) {
        getUserDeliveryAddr()
    }
})



// ------------------ 收货地址功能开始 ------------------
const deliveryAddrList = ref([])

// 请求收货地址
const getUserDeliveryAddr = async () => {
  const result = await reqUserDeliveryAddrListAPI({status: 1})
  deliveryAddrList.value = result.data.user_delivery_addrs != null ? result.data.user_delivery_addrs : []
  if (deliveryAddrList.value.length > 0) {
    let deliveryAddr = null
    deliveryAddrList.value.forEach((item) => {
        if (item.is_default == 1) {
        deliveryAddr = item
        }
    });

    if (!deliveryAddr) {
        deliveryAddr = deliveryAddrList.value[0]
    }


    currentAddrId.value = deliveryAddr.id
    userStore.setDeliveryAddr(deliveryAddr)
  }
}
// ------------------ 收货地址功能结束 ------------------



// ------------------ 选择收货地址开始 ------------------
const showAddDeliveryAddr = () => {
    getUserDeliveryAddr()
    drawer.value = true
}

// 定义处理选择地址事件
const handlerChooseDeliveryAddr = (item) => {
    currentAddrId.value = item.id
    userStore.setDeliveryAddr(item)
}
// ------------------ 选择收货地址结束 ------------------



// ------------------ 创建订单功能开始 ------------------
const handlerCreateOrder = async () => {
    if (!userStore.deliveryAddr) {
        ElNotification.error('请选择收货地址！')
        return false
    }

    // 下单参数
    let params = {
		platform: 1,
		username: userStore.profile.user.username,
		address_id: userStore.deliveryAddr.id,
        note: note.value
	}
	
	let result = null
	// 直接下单方式
	if (mode.value == 1) {
		const createOrderParams = orderStore.createOrderParams
		// 判断库存
		if (createOrderParams.num > createOrderParams.inventory_num) {
            ElNotification.error('库存不足！')
			return false
		}
		
		params.goods_sku_id = createOrderParams.goods_sku_id
		params.num = createOrderParams.num
		result = await reqGenerateOrderAPI(params)
	} else {// 购物车下单方式
		result = await reqCreateOrderAPI(params)
	}
	
    ElNotification.success('创建订单成功')
	
	// 跳转订单支付页面
    router.push({path: '/user/order/'+result.data.oid})
}
// ------------------ 创建订单功能结束 ------------------

</script>

<style scoped lang="scss">
.confirm-order-container {
    margin-bottom: 20px;
    padding-top: 195px;
    // 收货地址区域
    .address-wrap {
        background-color: #fff;
        padding: 10px;
        .title {
            display: flex;
            align-items: center;
            padding-bottom: 5px;
            border-bottom: 1px solid #f5f5f5;
            .iconfont {
                font-size: 30px;
                padding-right: 5px;
            }
            span {
                font-size: 20px;
            }
        }

        .content {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 10px 20px;
            cursor: pointer;
            .address-right {
                .name-box {
                    .name {
                        font-size: 18px;
                    }
                    .mobile {
                        margin-left: 6px;
                    }
                }
                .address {
                    padding-top: 10px;
                }

                .btn {
                    background-color: $main-color;
                    color: #fff;
                    height: 40px;
                    line-height: 40px;
                    width: 180px;
                    text-align: center;
                }
            }

            .iconfont {
                font-size: 20px;
            }
        }
    }

    // 商品信息区域
    .goods-wrap {
        background-color: #fff;
        padding: 10px;
        margin-top: 10px;
        .title {
            display: flex;
            align-items: center;
            padding-bottom: 5px;
            border-bottom: 1px solid #f5f5f5;
            .iconfont {
                font-size: 30px;
                padding-right: 5px;
            }
            span {
                font-size: 20px;
            }
        }

        .content {
            padding: 10px;
            display: flex;
            flex-wrap: wrap;
            .goods-item {
                display: flex;
                align-items: center;
                width: 48%;
                border: 1px solid #ccc;

                cursor: pointer;

                padding: 10px;
                margin: 10px 12px;

                .cover {
                    width: 80px;
                    height: 80px;
                    img {
                        width: 100%;
                        height: 100%;
                    }
                }

                .meta {
                    flex: 1;
                    display: flex;
                    flex-direction: column;

                    padding-left: 10px;
                    .name {
                        font-weight: bold;
                        line-height: 20px;
                    }
                    .sku-txt {
                        margin: 10px 0;
                        background-color: #f5f5f5;
                        padding: 5px;
                        color: #999;
                        line-height: 20px;
                    }
                    .price-wrap {
                        display: flex;
                        justify-content: space-between;
                        .price-box {
                            color: $price-color;
                            .symbol {
                                font-size: 14px;
                            }
                            .price {
                                font-size: 18px;
                            }
                        }

                        .num {
                            color: $main-color;
                        }
                    }
                }
            }
        }
    }

    .order-note-wrap {
        background-color: #fff;
        padding: 10px;
        margin-top: 2px;
    }

    // 结算区域
    .settlement-wrap {
        display: flex;
        justify-content: space-between;
        align-items: center;

        margin-top: 2px;
        background-color: #fff;
        height: 60px;
        line-height: 60px;
        padding: 0 40px;
        .amount-box {
            .text {
                font-weight: bold;
            }
            .symbol {
                font-size: 14px;
                color: $price-color;
            }
            .price {
                font-size: 18px;
                color: $price-color;
                font-weight: bold;
            }
        }
        .btn {
            cursor: pointer;
            display: block;
            width: 120px;
            background-color: $price-color;
            color: #fff;
            height: 50px;
            line-height: 50px;
            text-align: center;
        }
    }

    ::v-deep(.el-drawer__header) {
        margin-bottom: 0;
        padding-bottom: 12px;
        border-bottom: 1px solid #f5f5f5;
    }

    .header-wrap {
        font-weight: bold;
        text-align: center;
    }

    .content-wrap {
        .address-item {
            border: 1px solid #ccc;
            padding: 15px;
            margin-bottom: 10px;
            cursor: pointer;
            .top {
                display: flex;
                justify-content: space-between;
                .name {
                    font-size: 18px;
                }
                .mobile {
                    color: #999;
                }
            }
            .bottom {
                margin-top: 10px;
            }
        }
        .active {
            border: 1px solid $main-color;
        }

        .address-btn {
            display: flex;
            justify-content: center;
            margin-top: 20px;
            span {
                cursor: pointer;
                background-color: $main-color;
                color: #fff;
                text-align: center;
                padding: 10px 25px;
            }
        }
    }
}
</style>